//
//  RWCategoryList2ViewController.m
//  RedWine
//
//  Created by Liufangfang on 2017/1/23.
//  Copyright © 2017年 HuiBangKe. All rights reserved.
//

#import "RWCategoryList2ViewController.h"
#import "RWCategoryListTableViewCell.h"
#import "SegmentSuperViewController.h"
#import "RWGoodsModel.h"

#define kCategoryListBaseTag 600
#define kCategoryListTVHeaderHeight 40.*FTY_HEIGHT_BASE

@interface RWCategoryList2ViewController ()<RWCategoryListTableViewCellDelegate>{

    NSString *_subStr;
}


@end

@implementation RWCategoryList2ViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    [self loadDatas];
    [self setNavigation];
    [self setCategoryListUI];
    [self setTableViewHeader];
}

- (void)viewWillAppear:(BOOL)animated
{
     [self loadDatas];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{
 
    _categoryListModels = [NSMutableArray array];
}

- (void)loadDatas{
    
    FTYUser *user = [FTYUser sharedUser];
    NSString *memberID = @"";
    if (user.userID) {
        memberID = user.userID;
    } else {
        memberID = @"0";
    }
    
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=goodslist&member_id=%@&class=%@&sp_value_id=%@&%@", memberID, _className, _spValueID, _subStr] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            DLog(@"====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                [_categoryListModels removeAllObjects];
                [_categoryListModels addObjectsFromArray:[FTYBaseModel mj_objectWithKeyValues:result].info];
                
                
                [_categoryListTV reloadData];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        }  else {
            
            NSLog(@"分类列表请求错误：%@", error);
        }
    }];
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = @"分类列表";
}

- (void)setCategoryListUI{
    
    _categoryListTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT- FTY_TABBAR_HEIGHT-kCategoryListTVHeaderHeight) style:UITableViewStylePlain];
    [self.view addSubview:_categoryListTV];
    _categoryListTV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _categoryListTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _categoryListTV.dataSource = self;
    _categoryListTV.delegate = self;
}

- (void)setTableViewHeader
{
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, kCategoryListTVHeaderHeight)];
    headerV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    
    NSArray *titles = @[@"默认", @"关注度", @"价格"];
    NSArray *images = @[@"", @"paixu_x", @"paixu_x"];
    
    for (int i=0; i<3; i++) {
        
        UIButton *btn = [[UIButton alloc] init];
        [headerV addSubview:btn];
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -btn.imageView.bounds.size.width-40, 0, btn.imageView.bounds.size.width)];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, btn.titleLabel.bounds.size.width+40, 0, -btn.titleLabel.bounds.size.width)];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.titleLabel.font = FTY_FONTTSIZE(15);
        btn.tag = kCategoryListBaseTag + i;
        [btn addTarget:self action:@selector(headerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.mas_equalTo(0);
            make.left.mas_equalTo(FTY_SCREEN_WIDTH/3*i);
            make.width.mas_equalTo(FTY_SCREEN_WIDTH/3);
        }];
    }
    
    for (int i=0; i<2; i++) {
        
        UIView *line = [[UIView alloc] init];
        [headerV addSubview:line];
        line.backgroundColor = [UIColor blackColor];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(10.*FTY_HEIGHT_BASE);
            make.left.mas_offset(FTY_SCREEN_WIDTH/3*(i+1));
            make.bottom.mas_offset(-10.*FTY_HEIGHT_BASE);
            make.width.mas_offset(.5*FTY_WIDTH_BASE);
        }];
    }
    
    self.categoryListTV.tableHeaderView = headerV;
}

#pragma mark - Config Invoke Methods

#pragma mark - Notification Method

#pragma mark - Notification Invoke Methods

#pragma mark - <UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _categoryListModels.count;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//
//    return kCategoryListTVHeaderHeight;
//}

/*
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, kCategoryListTVHeaderHeight)];
    headerV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    
    NSArray *titles = @[@"默认", @"关注度", @"价格"];
    NSArray *images = @[@"", @"paixu_x", @"paixu_x"];
    
    for (int i=0; i<3; i++) {
        
        UIButton *btn = [[UIButton alloc] init];
        [headerV addSubview:btn];
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -btn.imageView.bounds.size.width-40, 0, btn.imageView.bounds.size.width)];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, btn.titleLabel.bounds.size.width+40, 0, -btn.titleLabel.bounds.size.width)];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
        btn.titleLabel.font = FTY_FONTTSIZE(15);
        btn.tag = kCategoryListBaseTag + i;
        [btn addTarget:self action:@selector(headerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.mas_equalTo(0);
            make.left.mas_equalTo(FTY_SCREEN_WIDTH/3*i);
            make.width.mas_equalTo(FTY_SCREEN_WIDTH/3);
        }];
    }
    
    for (int i=0; i<2; i++) {
        
        UIView *line = [[UIView alloc] init];
        [headerV addSubview:line];
        line.backgroundColor = [UIColor blackColor];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(10.*FTY_HEIGHT_BASE);
            make.left.mas_offset(FTY_SCREEN_WIDTH/3*(i+1));
            make.bottom.mas_offset(-10.*FTY_HEIGHT_BASE);
            make.width.mas_offset(.5*FTY_WIDTH_BASE);
        }];
    }
    
    return headerV;
}
 */

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 150.*FTY_HEIGHT_BASE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString * const categoryID = @"categoryID";
    RWCategoryListTableViewCell *categoryCell = [tableView dequeueReusableCellWithIdentifier:categoryID];
    if (!categoryCell) {
        
        categoryCell = [[RWCategoryListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:categoryID];
        categoryCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    categoryCell.delegate = self;
    categoryCell.tag = indexPath.row;
    [categoryCell loadDataWithModel:_categoryListModels[indexPath.row]];
    
    return categoryCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_categoryListModels[indexPath.row]];
    SegmentSuperViewController *detailPageVC = [[SegmentSuperViewController alloc] init];
    detailPageVC.hidesBottomBarWhenPushed = YES;
    detailPageVC.goodsID = goodsModel.goods_id;
    [self.navigationController pushViewController:detailPageVC animated:YES];
}
#pragma mark - <UITableViewDelegate>

#pragma mark - <RWCategoryListTableViewCellDelegate>

- (void)collection:(UIButton *)btn atIndex:(NSInteger)index{

    [self addFavorOrCancel:index];
}

- (void)shoppingCart:(UIButton *)btn atIndex:(NSInteger)index{
    
    [self addToShoppingCart:index];

    
}

#pragma mark - Private Invoke Methods

- (void)headerBtnAction:(UIButton *)btn{
    
    //默认排序 3是价格排序，5是关注排序
    NSInteger tag = btn.tag;
    NSString *subStr = @"";
    if (tag == 600) {
        //[self loadDatas];
    }else if (tag == 601){
        if (!btn.selected) {
            [btn setImage:[UIImage imageNamed:@"paixu_s"] forState:UIControlStateNormal];
            subStr = [NSString stringWithFormat:@"&type=5&fav=asc"];
        } else {
            [btn setImage:[UIImage imageNamed:@"paixu_x"] forState:UIControlStateNormal];
            subStr = [NSString stringWithFormat:@"&type=5&fav=desc"];
        }
    }else if (tag == 602){
        if (!btn.selected) {
            [btn setImage:[UIImage imageNamed:@"paixu_s"] forState:UIControlStateNormal];
            subStr = [NSString stringWithFormat:@"&type=3&goods_price=asc"];
        } else {
            [btn setImage:[UIImage imageNamed:@"paixu_x"] forState:UIControlStateNormal];
            subStr = [NSString stringWithFormat:@"&type=3&goods_price=desc"];
        }
    }
    
    btn.selected = !btn.selected;
    _subStr = subStr;
     [self loadDatas];
}

//加入收藏/取消收藏
- (void)addFavorOrCancel:(NSInteger)index
{
    NSLog(@"RWCategoryList2ViewController.h:addToFavor 加入收藏Btn Pressed!");
    RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_categoryListModels[index]];
    NSLog(@"收藏:index:%ld,coll:%ld",index,goodsModel.is_coll);
    if (goodsModel.is_coll == 0) {
        [self addFavorByGoodsId:index];
    }else if (goodsModel.is_coll ==1){
        [self cancelFavorByGoodsId:index];
    }
    
    
}
//加入购物车
- (void)addToShoppingCart:(NSInteger)index
{
    NSLog(@"RWCategoryList2ViewController.h:addToCart 加入购物车Btn Pressed!");
    RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_categoryListModels[index]];
    
//    [FTYShoppingCartPort requestShoppingCartWithProjectID:goodsModel.goods_id viewController:self block:^(BOOL isBool) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"AddShopCartNumberNotification" object:nil];
//    }];
    
    [FTYShoppingCartPort addShoppingCartWithProjectID:goodsModel.goods_id viewController:self block:^(BOOL isBool) {
        //[[NSNotificationCenter defaultCenter] postNotificationName:@"AddShopCartNumberNotification" object:nil];
    }];
}

//加入收藏
- (void)addFavorByGoodsId:(NSInteger)index
{
    RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_categoryListModels[index]];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=goodscoll&member_id=%@&goods_id=%@", [FTYUser sharedUser].userID, goodsModel.goods_id] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSLog(@"success=====%@", result);
            FTYErrorInfoModel *errModel = [FTYErrorInfoModel mj_objectWithKeyValues:[result objectForKey:@"err"]];
            if (0 == errModel.errorcode) {
                
                //goodsModel.is_coll = @"1";
                goodsModel.is_coll = 1;
                //重新为is_coll赋值
                NSMutableDictionary * dict = [_categoryListModels objectAtIndex:index];
                NSMutableDictionary *dict1 = [dict mutableCopy];
                [dict1 setObject:[NSNumber numberWithInteger:1] forKey:@"is_coll"];
                
                
                 [_categoryListModels replaceObjectAtIndex:index withObject:dict1];
                [self.categoryListTV reloadData];
                
            } else {
                
                [[FTYToastView alloc] addTitle:errModel.errorinfo addView:self.view];
            }
        } else {
            NSLog(@"error=====%@", error);
        }
    }];
}

//取消收藏
- (void)cancelFavorByGoodsId:(NSInteger)index
{
     RWGoodsModel *goodsModel = [RWGoodsModel mj_objectWithKeyValues:_categoryListModels[index]];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=cancelcoll&member_id=%@&goods_id=%@", [FTYUser sharedUser].userID, goodsModel.goods_id] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            NSLog(@"success=====%@", result);
            FTYErrorInfoModel *errModel = [FTYErrorInfoModel mj_objectWithKeyValues:[result objectForKey:@"err"]];
            if (0 == errModel.errorcode) {
                
                //goodsModel.is_coll = @"0";
                goodsModel.is_coll = 0;
                //重新为is_coll赋值
                
                NSMutableDictionary * dict = [_categoryListModels objectAtIndex:index];
                NSMutableDictionary *dict1 = [dict mutableCopy];
                 [dict1 setObject:[NSNumber numberWithInteger:0] forKey:@"is_coll"];
               
                [_categoryListModels replaceObjectAtIndex:index withObject:dict1];
                [self.categoryListTV reloadData];
                
            } else {
                
                [[FTYToastView alloc] addTitle:errModel.errorinfo addView:self.view];
            }
        } else {
            NSLog(@"error=====%@", error);
        }
    }];
}

@end
